// utils/api.js
class ApiService {
	constructor() {
		this.baseUrl = 'http://172.20.10.4:8002';
		this.agentId = '5b2cd0c8f00f4a3d8a7fb975a50a4abe'; // 智能体ID
		// 本地数据存储（作为缓存）
		this.store = {};
		// 初始化种子数据
		this.seedStart = '2024-01-01';
		this.seedEnd = '2024-12-31';
		// 初始化数据
		this.seedInitialData();
	}

	// 工具方法
	formatDate(date) {
		return new Date(date).toISOString().split('T')[0];
	}

	// HTTP请求封装
	async request(url, options = {}) {
		try {
			const response = await uni.request({
				url: url,
				method: options.method || 'GET',
				data: options.data,
				header: {
					'Content-Type': 'application/json',
					...options.header
				}
			});
			
			if (response.statusCode === 200) {
				return response.data;
			} else {
				throw new Error(`HTTP ${response.statusCode}: ${response.data?.msg || '请求失败'}`);
			}
		} catch (error) {
			console.error('API请求失败:', error);
			throw error;
		}
	}

	// 获取会话列表
	async getSessions(page = 1, limit = 10) {
		const url = `${this.baseUrl}/xiaozhi/public/agent/${this.agentId}/sessions?page=${page}&limit=${limit}`;
		return await this.request(url);
	}

	// 获取指定会话的聊天记录
	async getChatHistory(sessionId) {
		const url = `${this.baseUrl}/xiaozhi/public/agent/${this.agentId}/chat-history/${sessionId}`;
		return await this.request(url);
	}

	// 获取所有历史聊天记录（分页获取）
	async getAllChatHistory(parentId, maxPages = 5) {
		const allConversations = [];
		
		try {
			for (let page = 1; page <= maxPages; page++) {
				const sessionsResponse = await this.getSessions(page, 50);
				
				if (sessionsResponse.code === 0 && sessionsResponse.data && sessionsResponse.data.list.length > 0) {
					// 遍历当前页的所有会话
					for (const session of sessionsResponse.data.list) {
						try {
							const chatResponse = await this.getChatHistory(session.sessionId);
							
							if (chatResponse.code === 0 && chatResponse.data) {
								// 转换数据格式
								const formattedConversations = chatResponse.data.map(chat => ({
									time: new Date(chat.createdAt).toLocaleTimeString('zh-CN', { 
										hour: '2-digit', 
										minute: '2-digit',
										hour12: false 
									}),
									content: chat.content,
									speaker: chat.chatType === 1 ? parentId : 'agent',
									chatType: chat.chatType,
									audioId: chat.audioId,
									macAddress: chat.macAddress,
									createdAt: chat.createdAt,
									sessionId: session.sessionId
								}));
								
								allConversations.push(...formattedConversations);
							}
						} catch (error) {
							console.warn(`获取会话 ${session.sessionId} 的聊天记录失败:`, error);
							continue;
						}
					}
				} else {
					// 没有更多数据了
					break;
				}
			}
			
			// 按时间排序
			allConversations.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
			
		return allConversations;
	} catch (error) {
		console.error('获取所有聊天记录失败:', error);
		return [];
	}
}

	// 获取指定日期范围的聊天记录
	async getChatHistoryByDateRange(parentId, startDate, endDate) {
		const allConversations = await this.getAllChatHistory(parentId);
		
		return allConversations.filter(chat => {
			const chatDate = new Date(chat.createdAt).toISOString().split('T')[0];
			return chatDate >= startDate && chatDate <= endDate;
		});
	}

	addDays(dateStr, d) {
		const d0 = new Date(dateStr);
		d0.setDate(d0.getDate() + d);
		return this.formatDate(d0);
	}

	// 种子数据生成
	seedInitialData() {
		// 生成一个月的随机数据
		const today = new Date();
		for (let i = 29; i >= 0; i--) {
			const d = new Date(today);
			d.setDate(d.getDate() - i);
			const dateStr = this.formatDate(d);
			this.ensureDailyData('mother', dateStr);
			this.ensureDailyData('father', dateStr);
		}
	}

	// 确保每日数据存在
	ensureDailyData(parentId, dateStr) {
		if (!this.store[parentId]) {
			this.store[parentId] = {};
		}
		if (!this.store[parentId][dateStr]) {
			// 生成随机对话
			const conversationCount = Math.floor(Math.random() * 5) + 1;
			const conversations = [];
			for (let i = 0; i < conversationCount; i++) {
				const hour = Math.floor(Math.random() * 12) + 8; // 8-20点
				const minute = Math.floor(Math.random() * 60);
				conversations.push({
					time: `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`,
					content: this.generateRandomContent(parentId),
					speaker: parentId
				});
			}
			// 按时间排序
			conversations.sort((a, b) => a.time.localeCompare(b.time));
			this.store[parentId][dateStr] = conversations;
		}
	}

	// 生成随机对话内容
	generateRandomContent(parentId) {
		const motherContents = [
			'今天过得怎么样？学习压力大吗？',
			'记得按时吃饭，别熬夜太晚了。',
			'天气变凉了，记得多穿点衣服。',
			'周末回家吗？妈妈做你爱吃的菜。',
			'最近学习累不累？要注意休息。',
			'有没有交到新朋友？',
			'别总是玩手机，多看看书。',
			'钱够花吗？不够的话和妈妈说。',
			'今天心情怎么样？有什么开心的事吗？',
			'最近身体怎么样？有没有哪里不舒服？'
		];
		const fatherContents = [
			'学习要认真，但也别给自己太大压力。',
			'注意安全，晚上别单独出门。',
			'有什么困难要及时和爸爸说。',
			'今天学了什么新知识？',
			'周末有空一起去运动吗？',
			'记得保持良好的作息习惯。',
			'遇到问题要学会独立思考。',
			'和同学要好好相处。',
			'要学会理财，不要乱花钱。',
			'爸爸相信你能做得很好！'
		];
		const contents = parentId === 'mother' ? motherContents : fatherContents;
		return contents[Math.floor(Math.random() * contents.length)];
	}

	// 获取父母对话（使用真实API数据）
	async getParentConversations(parentId, dateStr) {
		try {
			// 首先尝试从API获取数据
			const sessionsResponse = await this.getSessions(1, 50);
			
			if (sessionsResponse.code === 0 && sessionsResponse.data && sessionsResponse.data.list) {
				const conversations = [];
				
				// 遍历所有会话，查找指定日期的聊天记录
				for (const session of sessionsResponse.data.list) {
					try {
						const chatResponse = await this.getChatHistory(session.sessionId);
						
						if (chatResponse.code === 0 && chatResponse.data) {
							// 过滤指定日期的聊天记录
							const dayConversations = chatResponse.data.filter(chat => {
								const chatDate = new Date(chat.createdAt).toISOString().split('T')[0];
								return chatDate === dateStr;
							});
							
							// 转换数据格式以匹配现有结构
							const formattedConversations = dayConversations.map(chat => ({
								time: new Date(chat.createdAt).toLocaleTimeString('zh-CN', { 
									hour: '2-digit', 
									minute: '2-digit',
									hour12: false 
								}),
								content: chat.content,
								speaker: chat.chatType === 1 ? parentId : 'agent', // 1=用户，2=智能体
								chatType: chat.chatType,
								audioId: chat.audioId,
								macAddress: chat.macAddress,
								createdAt: chat.createdAt
							}));
							
							conversations.push(...formattedConversations);
						}
					} catch (error) {
						console.warn(`获取会话 ${session.sessionId} 的聊天记录失败:`, error);
						continue;
					}
				}
				
				// 按时间排序
				conversations.sort((a, b) => a.time.localeCompare(b.time));
				
				// 缓存数据
				if (!this.store[parentId]) {
					this.store[parentId] = {};
				}
				this.store[parentId][dateStr] = conversations;
				
				return { conversations };
			}
		} catch (error) {
			console.error('获取API数据失败，使用本地数据:', error);
		}
		
		// 如果API失败，回退到本地数据
		this.ensureDailyData(parentId, dateStr);
		return { conversations: this.store[parentId][dateStr] || [] };
	}

	// 调用大模型分析情绪（保持你现有的 analyzeEmotion 实现）
	async analyzeEmotion(conversations) {
		// 简化版情绪映射与规则，覆盖常见表达
		const dict = {
			'开心': { emotion: '开心', emoji: '😊', score: 3, desc: '积极愉悦' },
			'愉快': { emotion: '开心', emoji: '😊', score: 3, desc: '心情愉悦' },
			'高兴': { emotion: '开心', emoji: '😊', score: 3, desc: '心情愉悦' },
			'担心': { emotion: '担忧', emoji: '😰', score: -1, desc: '表达担忧' },
			'担忧': { emotion: '担忧', emoji: '😰', score: -1, desc: '表达担忧' },
			'焦虑': { emotion: '焦虑', emoji: '😔', score: -2, desc: '焦虑不安' },
			'孤单': { emotion: '孤独', emoji: '😢', score: -2, desc: '感到孤独' },
			'孤独': { emotion: '孤独', emoji: '😢', score: -2, desc: '感到孤独' },
			'疲惫': { emotion: '疲惫', emoji: '😴', score: -1, desc: '身心疲惫' },
			'累': { emotion: '疲惫', emoji: '😴', score: -1, desc: '身心疲惫' },
			'想你': { emotion: '想念', emoji: '🥺', score: 1, desc: '表达思念' },
			'想家': { emotion: '想念', emoji: '🥺', score: 1, desc: '表达思念' },
			'怀念': { emotion: '怀念', emoji: '😌', score: 0, desc: '回味往昔' },
			'羡慕': { emotion: '羡慕', emoji: '😔', score: -1, desc: '表达羡慕' },
			'关心': { emotion: '关心', emoji: '😟', score: 2, desc: '关心家人' },
		};

		const fallback = { emotion: '平静', emoji: '😐', score: 1, desc: '情绪较为平稳' };

		const analyzed = conversations.map(item => {
			const key = Object.keys(dict).find(k => item.content.includes(k));
			const picked = key ? dict[key] : fallback;
			return {
				...item,
				emotion: picked.emotion,
				emoji: picked.emoji,
				confidence: 0.8,
				description: picked.desc
			};
		});

		const overall = this.calculateOverallEmotion(analyzed.map(a => a.emotion));
		return { conversations: analyzed, overall };
	}

	// 计算整体情绪（保留你已有实现）
	calculateOverallEmotion(emotions) {
		const emotionScores = {
			'开心': 3,
			'关心': 2,
			'想念': 1,
			'怀念': 0,
			'平静': 1,
			'担忧': -1,
			'疲惫': -1,
			'羡慕': -1,
			'焦虑': -2,
			'孤独': -2,
			'低落': -2
		};
		if (!emotions || emotions.length === 0) {
			return { emotion: '平静', emoji: '😐', level: '一般', color: '#FF9800' };
		}
		const total = emotions.reduce((s, e) => s + (emotionScores[e] ?? 0), 0);
		const avg = total / emotions.length;
		if (avg >= 2) return { emotion: '开心', emoji: '😊', level: '良好', color: '#4CAF50' };
		if (avg >= 0) return { emotion: '平静', emoji: '😐', level: '一般', color: '#FF9800' };
		return { emotion: '低落', emoji: '😔', level: '需要关注', color: '#F44336' };
	}

	// 兼容旧接口名
	async getMoodHistory(parentId, days = 7) {
		return await this.getLastNDaysHistory(parentId, days);
	}

	// 3) 获取今日情绪
	async getTodayMood(parentId) {
		const date = this.formatDate(new Date());
		const { conversations } = await this.getParentConversations(parentId, date);
		const analysis = await this.analyzeEmotion(conversations);
		return analysis.overall;
	}

	// 4) 获取近N天（从今天往回数）
	async getLastNDaysHistory(parentId, n = 7) {
		const history = [];
		const today = new Date();
		
		// 首先获取所有聊天记录
		const allConversations = await this.getAllChatHistory(parentId);
		
		for (let i = n - 1; i >= 0; i--) {
			const d = new Date(today);
			d.setDate(d.getDate() - i);
			const dateStr = this.formatDate(d);
			
			// 从所有聊天记录中过滤出当天的记录
			const dayConversations = allConversations.filter(chat => {
				const chatDate = new Date(chat.createdAt).toISOString().split('T')[0];
				return chatDate === dateStr;
			});
			
			const analysis = await this.analyzeEmotion(dayConversations);
			history.push({
				date: dateStr,
				mood: analysis.overall,
				conversations: analysis.conversations
			});
		}
		return history;
	}

	// 5) 获取近7天曲线序列（带分数与标签）
	emotionToScore(level, emotion) {
		// 分数用于绘图：良好=80，一般=60，需要关注=40，微调不同情绪
		const base = level === '良好' ? 80 : level === '一般' ? 60 : 40;
		const tweak = {
			'开心': 8, '关心': 2, '想念': 0, '怀念': 0,
			'疲惫': -4, '羡慕': -2, '焦虑': -8, '孤独': -10, '平静': 0, '低落': -12
		}[emotion] || 0;
		return Math.max(30, Math.min(95, base + tweak));
	}

	async getSevenDaySeries(parentId) {
		const data = await this.getLastNDaysHistory(parentId, 7);
		return data.map(item => ({
			date: item.date,
			score: this.emotionToScore(item.mood.level, item.mood.emotion),
			emoji: item.mood.emoji,
			emotion: item.mood.emotion,
			level: item.mood.level
		}));
	}
}

export default new ApiService();